package com.magic.service.user;

import java.math.BigDecimal;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.magic.auth.TokenUtil;
import com.magic.consts.ExchangeEnum;
import com.magic.entity.game.Game;
import com.magic.entity.game.GameHistory;
import com.magic.entity.gift.Gift;
import com.magic.entity.user.Address;
import com.magic.entity.user.ExchangeHistory;
import com.magic.entity.user.Flower;
import com.magic.entity.user.User;
import com.magic.entity.user.UserGame;
import com.magic.redis.jedis.JedisService;
import com.magic.repository.IAddressRepository;
import com.magic.repository.IExchangeHistoryRepository;
import com.magic.repository.IFlowerRepository;
import com.magic.repository.IGameHistoryRepository;
import com.magic.repository.IGameRepository;
import com.magic.repository.IGiftRepository;
import com.magic.repository.IUserGameRepository;
import com.magic.repository.IUserRepository;
import com.magic.result.Result;

/**
 * ClassName: UserService <br/>
 * Function: userService. <br/>
 * date: 2018年10月16日 下午2:53:25 <br/>
 * 
 * @author lishuai11
 * @version
 * @since JDK 1.8
 */
@Service("userService")
public class UserService {

	private static final Logger logger = LoggerFactory.getLogger(UserService.class);

	@Autowired
	private JedisService jedisService;

	@Autowired
	private IUserRepository userRepository;

	@Autowired
	private IAddressRepository addressRepository;

	@Autowired
	private IGiftRepository giftRepository;

	@Autowired
	private IExchangeHistoryRepository exchangeHistoryRepository;

	@Autowired
	private IGameRepository gameRepository;

	@Autowired
	private IGameHistoryRepository gameHistoryRepository;

	@Autowired
	private IFlowerRepository flowerRepository;

	@Autowired
	private IUserGameRepository userGameRepository;

	public Result findByUserId(int userId, String token) {
		try {
			if (!TokenUtil.resourceAudit(token, userId)) {
				return Result.fail(Result.CLIENT_ERROR, "Authorization is not valid  | userId is not valid");
			}
			return Result.success("success", findOne(userId));
		} catch (Exception e) {
			logger.error("UserService.findByUserId()方法异常{}:{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	public Result updateUser(User user, String token) {
		try {
			if (!TokenUtil.resourceAudit(token, user.getUserId())) {
				return Result.fail(Result.CLIENT_ERROR, "Authorization is not valid  | userId is not valid");
			}
			User dbUser = findOne(user.getUserId());
			if (dbUser == null) {
				return Result.fail(Result.CLIENT_ERROR, "用户不存在");
			}
			dbUser.setCity(user.getCity());
			dbUser.setGender(user.getGender());
			dbUser.setIcon(user.getIcon());
			dbUser.setNickName(user.getNickName());
			dbUser.setMobile(user.getMobile());
			userRepository.save(dbUser);
			return Result.success("success");
		} catch (Exception e) {
			logger.error("UserService.updateUser()方法异常{}:{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	public Result flowerByUserId(int userId, String token) {
		try {
			if (!TokenUtil.resourceAudit(token, userId)) {
				return Result.fail(Result.CLIENT_ERROR, "Authorization is not valid  | userId is not valid");
			}
			Flower flower = findFlowerByUserId(userId);
			if (flower == null) {
				return Result.fail(Result.CLIENT_ERROR, "用户不存在");
			}
			return Result.success("success", flower);
		} catch (Exception e) {
			logger.error("UserService.seedByUserId()方法异常{}:{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	/**
	 * 
	 * addressList:(地址列表). <br/>
	 * 
	 * @author lishuai11
	 * @return
	 * @since JDK 1.8
	 */
	public Result addressList(int userId, String token) {
		try {
			if (!TokenUtil.resourceAudit(token, userId)) {
				return Result.fail(Result.CLIENT_ERROR, "Authorization is not valid  | userId is not valid");
			}
			List<Address> list = findAddressByUserId(userId);
			return Result.success("成功", list);
		} catch (Exception e) {
			logger.error("UserService.addressList()方法异常{}:{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	/**
	 * 
	 * addAddress:(添加地址). <br/>
	 * 
	 * @author lishuai11
	 * @param address
	 * @since JDK 1.8
	 */
	@Transactional
	public Result addAddress(Address address, String token) {
		try {
			if (!TokenUtil.resourceAudit(token, address.getUserId())) {
				return Result.fail(Result.CLIENT_ERROR, "Authorization is not valid  | userId is not valid");
			}
			address = addressRepository.save(address);
			if (address.isSelect()) {
				List<Address> list = findAddressNotContainAddressId(address.getAddressId());
				if (list != null && !list.isEmpty()) {
					for (Address address2 : list) {
						address2.setSelect(false);
						addressRepository.save(address2);
					}
				}
			}
			return Result.success("success");
		} catch (Exception e) {
			logger.error("UserService.addAddress()方法异常{}:{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	/**
	 * 
	 * updateAddress:(更新地址). <br/>
	 * 
	 * @author lishuai11
	 * @param address
	 * @since JDK 1.8
	 */
	@Transactional
	public Result updateAddress(Address address, String token) {
		try {
			if (!TokenUtil.resourceAudit(token, address.getUserId())) {
				return Result.fail(Result.CLIENT_ERROR, "Authorization is not valid  | userId is not valid");
			}
			Address dbAddress = findAddressOne(address.getAddressId());
			if (dbAddress == null) {
				return Result.fail(Result.CLIENT_ERROR, "收货地址不存在");
			}
			dbAddress.setCity(address.getCity());
			dbAddress.setCode(address.getCode());
			dbAddress.setDetail(address.getDetail());
			dbAddress.setMobile(address.getMobile());
			dbAddress.setProvince(address.getProvince());
			dbAddress.setReceiveName(address.getReceiveName());
			dbAddress.setUnit(address.getUnit());
			dbAddress.setSelect(address.isSelect());
			dbAddress = addressRepository.save(dbAddress);
			if (dbAddress.isSelect()) {
				List<Address> list = findAddressNotContainAddressId(dbAddress.getAddressId());
				if (list != null && !list.isEmpty()) {
					for (Address address2 : list) {
						address2.setSelect(false);
						addressRepository.save(address2);
					}
				}
			}
			return Result.success("success");
		} catch (Exception e) {
			logger.error("UserService.updateAddress()方法异常{}:{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	/**
	 * 
	 * deleteAddress:(删除地址). <br/>
	 * 
	 * @author lishuai11
	 * @param addressId
	 * @return
	 * @since JDK 1.8
	 */
	public Result deleteAddress(int addressId, String token) {
		try {
			Address address = findAddressOne(addressId);
			if (address == null) {
				return Result.fail(Result.CLIENT_ERROR, "收货地址不存在");
			}
			if (!TokenUtil.resourceAudit(token, address.getUserId())) {
				return Result.fail(Result.CLIENT_ERROR, "Authorization is not valid  | userId is not valid");
			} else {
				addressRepository.delete(addressId);
				return Result.success("删除成功");
			}
		} catch (Exception e) {
			logger.error("UserService.deleteAddress()方法异常{}:{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	/**
	 * 
	 * deleteAllAddress:(清空地址). <br/>
	 * 
	 * @author lishuai11
	 * @param userId
	 * @return
	 * @since JDK 1.8
	 */
	public Result deleteAllAddress(int userId, String token) {
		try {
			if (!TokenUtil.resourceAudit(token, userId)) {
				return Result.fail(Result.CLIENT_ERROR, "Authorization is not valid  | userId is not valid");
			}
			addressRepository.deleteByUserId(userId);
			return Result.success("已清空");
		} catch (Exception e) {
			logger.error("UserService.deleteAddress()方法异常{}:{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	/**
	 * 
	 * logout:(退出). <br/>
	 * 
	 * @author lishuai11
	 * @param token
	 * @return
	 * @since JDK 1.8
	 */
	public Result logout(String token, int userId) {
		try {
			if (jedisService.isExist(token)) {
				String indexToken = TokenUtil.getToken(userId);
				if (TokenUtil.resourceAudit(indexToken, userId)) {
					jedisService.delete(token);
					return Result.success("成功");
				} else {
					return Result.fail(Result.CLIENT_ERROR, "Authorization is not valid  | userId is not valid");
				}
			} else {
				return Result.fail(Result.CLIENT_ERROR, "无效token");
			}

		} catch (Exception e) {
			logger.error("UserService.logout()方法异常{}:{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	public Result exchangeHistory(int userId, int pageNum, int pageSize, String token) {
		try {
			if (!TokenUtil.resourceAudit(token, userId)) {
				return Result.fail(Result.CLIENT_ERROR, "Authorization is not valid  | userId is not valid");
			}
			pageNum = pageNum * pageSize;
			return Result.success("成功", exchangeHistoryRepository.pageSearchByUserId(pageNum, pageSize, userId));
		} catch (Exception e) {
			logger.error("UserService.exchangeHistory()方法异常{}:{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	@Transactional
	public synchronized Result exchange(ExchangeHistory exchangeHistory, String token) {
		try {
			if (!TokenUtil.resourceAudit(token, exchangeHistory.getUserId())) {
				return Result.fail(Result.CLIENT_ERROR, "Authorization is not valid  | userId is not valid");
			}
			Flower flower = findFlowerByUserId(exchangeHistory.getUserId());
			if (flower == null) {
				return Result.fail(Result.CLIENT_ERROR, "非法userId");
			}
			Gift gift = findGiftOne(exchangeHistory.getGiftId());
			if (gift == null) {
				return Result.fail(Result.CLIENT_ERROR, "非法giftId");
			}
			if (flower.getEarnSeed().compareTo(gift.getGiftPrice()) >= 0) {
				flower.setEarnSeed(flower.getEarnSeed().subtract(gift.getGiftPrice()));
				flower.setAllSeed(flower.getEarnSeed().add(flower.getRechargeSeed()));
				flower = flowerRepository.save(flower);
			} else {
				return Result.fail(Result.MONEY_ERROR, "收益花种不足,您可参与游戏获取");
			}
			exchangeHistory.setStatus(ExchangeEnum.TOSEND.getValue());
			return Result.success("成功", exchangeHistoryRepository.save(exchangeHistory));
		} catch (Exception e) {
			logger.error("UserService.exchange()方法异常{}:{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	public Result userGame(int userId, int pageNum, int pageSize, String token) {
		try {
			if (!TokenUtil.resourceAudit(token, userId)) {
				return Result.fail(Result.CLIENT_ERROR, "Authorization is not valid  | userId is not valid");
			}
			pageNum = pageNum * pageSize;
			List<UserGame> list = userGameRepository.pageSearchUserGame(pageNum, pageSize, userId);
			if (list == null || list.isEmpty()) {
				return Result.success("成功", list);
			} else {
				List<UserGame> expireUserGame = Lists.newArrayList();
				Game game;
				GameHistory endGameHistory;
				UserGame endUserGame;
				for (UserGame userGame : list) {
					game = findGameOne(userGame.getGameId());
					if (game != null) {
						if (game.getEnd()) {
							endGameHistory = findEndGameHistory(game.getGameId());
							if (endGameHistory == null) {
								userGame.setEndUser("");
								userGame.setEndUserInput(new BigDecimal("0.00"));
								userGame.setEndUserReceiver(new BigDecimal("0.00"));
							} else {
								userGame.setEndUser(endGameHistory.getMobile());
								endUserGame = findUserGameByUserIdAndGameId(endGameHistory.getUserId(),
										endGameHistory.getGameId());
								userGame.setEndUserInput(endUserGame.getEndUserInput());
								userGame.setEndUserReceiver(endUserGame.getUserReceiver());
							}
							expireUserGame.add(userGame);
						}
					}
				}
				return Result.success("成功", expireUserGame);
			}
		} catch (Exception e) {
			logger.error("UserService.userGanmeHistory()方法异常{}:{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	public Result getUserGameSeeds(int userId, int gameId, String token) {
		try {
			if (!TokenUtil.resourceAudit(token, userId)) {
				return Result.fail(Result.CLIENT_ERROR, "Authorization is not valid  | userId is not valid");
			}
			UserGame userGame = getUserGameOne(userId, gameId);
			return Result.success("成功", userGame);
		} catch (Exception e) {
			logger.error("UserService.userGanmeHistory()方法异常{}:{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	public List<Address> findAddressByUserId(int userId) {
		return addressRepository.findByUserId(userId);
	}

	public User findOne(int userId) {
		return userRepository.findOne(userId);
	}

	public Address findAddressOne(int addressId) {
		return addressRepository.findOne(addressId);
	}

	public List<Address> findAddressNotContainAddressId(int addressId) {
		return addressRepository.findAddressNotContainAddressId(addressId);
	}

	public ExchangeHistory findExchangeHistoryOne(int exchangeId) {
		return exchangeHistoryRepository.findOne(exchangeId);
	}

	public Flower findFlowerByUserId(int userId) {
		List<Flower> flowers = flowerRepository.findByUserId(userId);
		if (flowers == null || flowers.isEmpty()) {
			return null;
		}
		return flowers.get(0);
	}

	public Gift findGiftOne(int giftId) {
		return giftRepository.findOne(giftId);
	}

	public Game findGameOne(int gameId) {
		return gameRepository.findOne(gameId);
	}

	public UserGame findUserGameByUserIdAndGameId(int userId, int gameId) {
		List<UserGame> list = userGameRepository.findByUserIdAndGameId(userId, gameId);
		if (list != null && !list.isEmpty()) {
			return list.get(0);
		} else {
			return null;
		}
	}

	public GameHistory findEndGameHistory(int gameId) {
		List<GameHistory> list = gameHistoryRepository.findByGameId(gameId);
		if (list != null && !list.isEmpty()) {
			return list.get(0);
		} else {
			return null;
		}
	}

	public UserGame getUserGameOne(int userId, int gameId) {
		List<UserGame> userGames = userGameRepository.findByUserIdAndGameId(userId, gameId);
		if (userGames != null && !userGames.isEmpty()) {
			return userGames.get(0);
		} else {
			return null;
		}
	}

}
